# -*- coding: utf-8 -*-
"""
Created on Sat May 18 15:42:29 2019

目标:
    读取163网站上主要财务指标数据
    
读取的数据类型
    lrb - 利润表
    zcfzb - 资产负债表
    xjllb - 现金流量表
    cwbbzy - 财务报表摘要
    zycwzb - 主要财务指标
@author: yaoyu
"""

import os
import numpy as np
import pandas as pd
from pandas.compat import StringIO
import requests

def read_csv_163_file(data_file, transpose=True):
    assert os.path.isfile(data_file), data_file
    return CN163Tool(transpose).read_csv(data_file)

def read_csv_163_data(data, transpose=True):
    assert isinstance(data, str)
    return CN163Tool(transpose).read_csv(StringIO(data))

class CN163Tool(object):
    def __init__(self, transpose=True):
        self.transpose = transpose
        
    def read_stock(self, stock_code, name='zycwzb'):
        r = requests.get('http://quotes.money.163.com/service/%s_%s.html?type=report' % (name, stock_code))
        if r.status_code == 200:
            return self.read_csv(StringIO(r.text.strip()))
        else:
            r.raise_for_status()
    
    def read_csv(self, filepath_or_buffer, *args, **kwargs):
        df = pd.read_csv(filepath_or_buffer, *args, **kwargs).replace('--', np.nan)
        if self.transpose:
            df = df.set_index(df.columns[0]).stack().unstack(0)
        df = df.apply(pd.to_numeric, errors='ignore')
        return df

def main2():
    data_file = r'zycwzb_600080.csv'
    df = read_csv_163_file(data_file)
    #df.to_excel('zycwzb_600080.xls')
    return df

def main():
    stock='300021'
    name = 'zcfzb'
    df = CN163Tool().read_stock(stock, name)
    print(df)
    return df

if __name__ == '__main__':
    df=main()
